﻿
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using WebSilverlight.Web;
using System.Collections;
using System.ServiceModel.DomainServices.Client;
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.IO;

namespace WebSilverlight.Views
{
	public partial class ClienteWorkWithEx : Page 
	{
	#region Properties	
	 //   private ClienteDomainContext dcClienteContext1;
		int itemCount;
		public int ItemCount
		{
			get { return itemCount; }
			set
			{
				if (itemCount != value)
				{                    
					//pager.NumericButtonCount = itemCount / 6;
					itemCount = value;
					//RaisePropertyChanged(ItemCountChangedEventArgs);         // INotifyPropertyChanged                 
				}
			}
		}
	#endregion

        public ClienteWorkWithEx()
		{
			InitializeComponent();            
			if (dcClienteContext1 == null)
				dcClienteContext1 = new ClienteDomainContext();
		}
		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			
		}        
		private void SubmitButton_Click(object sender, RoutedEventArgs e)
		{            
			ddsCliente1.SubmitChanges();
		}
		private void AddNew_Click(object sender, RoutedEventArgs e)
		{
			CallEdit(false, true);
		}

		/*  // LoadingData="ddsCliente1_LoadingData" LoadedData="ddsCliente1_LoadedData"  
		 private void ddsCliente1_LoadingData(object sender, LoadingDataEventArgs e)
		 {
			 //BusyIndicator1.IsBusy = true;
		 }*/
		 private void ddsCliente1_LoadedData(object sender, LoadedDataEventArgs e)
		 {             
			 //BusyIndicator1.IsBusy  = false;
			 if(!e.HasError)
			 {
				 InvokeOperation<int> res = dcClienteContext1.ItemCount();
				 res.Completed += new EventHandler( ItemCountCompleted );
			 }             
		 }
		 /**/
		 

		private void ItemCountCompleted (object sender, EventArgs e)
		{
			InvokeOperation<int> op = (InvokeOperation<int>)sender;
			if (!op.HasError)
				ItemCount = op.Value;            
		}
		
		 private void OpenButton_Click(object sender, RoutedEventArgs e)
		 {
			 CallEdit(true, false);
		 }
		 private void EditButton_Click(object sender, RoutedEventArgs e)
		 {
			 CallEdit(false, false);
		 }
		 private void CallEdit(bool IsReadOnly, bool IsNew)
		 {
			 ClienteWrapper current = null;
			 bool error = false;
			 IList list = dataGridCliente1.SelectedItems;

			 if (IsNew)
				 current = new ClienteWrapper();
			 else
			 {
				 if (list.Count != 1)
				 {                     
					 System.Windows.MessageBox.Show("select one element");
					 error = true;
				 }
				 else
					 current = (ClienteWrapper)list[0];
			 }

			 if (!error)
			 {   
				 if (ddsCliente1.HasChanges)
				 {                     
					 System.Windows.MessageBox.Show("Changes Discarded");                     
					 dataGridCliente1.CancelEdit();
					 dataFormCliente1.CancelEdit();
					 ddsCliente1.RejectChanges();
				 }                

				 var editw = new ClienteEditFlip(!IsReadOnly);
				 editw.Current = current;
				 editw.DomainContext = this.dcClienteContext1;
				 editw.DDS = this.ddsCliente1;
				 editw.IsNew = IsNew;
				 editw.Show();
			 }
		 }

		 private void DeleteButton_Click(object sender, RoutedEventArgs e)
		 {
			 
		 }

		 private void CancelEditButton_Click(object sender, RoutedEventArgs e)
		 {             
			 if (ddsCliente1.HasChanges)
			 {
				 //Mensaje de Advertencia?
				 dataGridCliente1.CancelEdit();
				 dataFormCliente1.CancelEdit();
				 ddsCliente1.RejectChanges();
			 }
		 }

		 private void ShowDetail_Click(object sender, RoutedEventArgs e)
		 {
			 if (this.DetailContent.Visibility == System.Windows.Visibility.Visible)
				 this.DetailContent.Visibility = System.Windows.Visibility.Collapsed;
			 else
				 this.DetailContent.Visibility = System.Windows.Visibility.Visible;
		 }

		 private void PaisComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		 {
			 if (e.AddedItems.Count != 0)
			 {
				 PaisWrapper pais = (PaisWrapper)e.AddedItems[0];
				 ClienteWrapper current = null;
				 IList list = dataGridCliente1.SelectedItems;

				 if (list.Count != 1)
				 {
					 System.Windows.MessageBox.Show("Error");
				 }
				 else
				 {
					 current = (ClienteWrapper)list[0];
					 current.PaisNombre = pais.PaisNombre;
				 }
			 }
		 }
		/*
		 private void ddsPais1_LoadedData(object sender, LoadedDataEventArgs e)
		 {
			 var component = this.dataGridCliente1.FindName("paisCombo");
			 if (component != null)
			 {
				 ComboBox combo = (ComboBox)component;
				 combo.SelectedValue = Current.PaisId;
			 }
			 else System.Windows.MessageBox.Show("Upss...");
		 }
		*/

         private void PruabIM(object sender, RoutedEventArgs e)
         {
             ClienteWrapper cli = (ClienteWrapper)dataGridCliente1.SelectedItem;
             if (cli.ClientePicture != null)
             {
                 Stream str = new MemoryStream(cli.ClientePicture);
                 BitmapImage pic = new BitmapImage();
                 pic.SetSource(str);

                // ImageProfileControl.Source = pic;
             }
             else
             {
                // WriteableBitmap wb = new WriteableBitmap(ImageProfileControl2, null);
                 WriteableBitmap wb = new WriteableBitmap(null, null);
                 byte[] bmpBytes = ToByteArray(wb);
                 cli.ClientePicture = bmpBytes;
             }
         }

         public byte[] ToByteArray(WriteableBitmap bmp)
         {
             int[] p = bmp.Pixels;
             int len = p.Length * 4;
             byte[] result = new byte[len]; // ARGB
             Buffer.BlockCopy(p, 0, result, 0, len);
             return result;
         }
         public void FromByteArray(WriteableBitmap bmp, byte[] buffer)
         {
             Buffer.BlockCopy(buffer, 0, bmp.Pixels, 0, buffer.Length);
         }

        //public static byte[] ToByteArray(this WriteableBitmap bmp)
        //{
        //    int[] p = bmp.Pixels;
        //    int len = p.Length * 4;
        //    byte[] result = new byte[len]; // ARGB
        //    Buffer.BlockCopy(p, 0, result, 0, len);
        //    return result;
        //}        
        //public static void FromByteArray(this WriteableBitmap bmp, byte[] buffer)
        //{
        //    Buffer.BlockCopy(buffer, 0, bmp.Pixels, 0, buffer.Length);
        //}

         void prompt_Closed(object sender, EventArgs e)
         {
             var prompt = (PaisPrompt)sender;
             prompt.Closed -= this.prompt_Closed;

             if (prompt.Selected != null)
             {
                 ClienteWrapper current = (ClienteWrapper)this.dataGridCliente1.SelectedItem;
                 current.PaisId = prompt.Selected.PaisId;
                 current.PaisNombre = prompt.Selected.PaisNombre;
             }
         }

         private void PaisPrompt(object sender, RoutedEventArgs e)
         {
             var prompt = new PaisPrompt();
             prompt.Closed += new EventHandler(prompt_Closed);
             prompt.Show();
         } 
	}
}
